﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Spelprojekt
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D BGTexture;
        Texture2D StartSplash;
        Texture2D EndSplash;
        Texture2D Blast;
        Player Spaceship;
        float totalTime = 0.0f;
        public enum EnemyType { Ship }
        List<Fireball> playerFireballList = new List<Fireball>();
        List<Fireball> enemyFireballList = new List<Fireball>();
        List<Enemy> enemyShipList = new List<Enemy>();
        Texture2D EnemyShip;
        Texture2D EBlast;
        Random rnd = new Random();
        float buttonFireDelay = 0.0f;
        SpriteFont font, menufont;
        int score = 0;
        public enum GameState
        { StartScreen, Running, EndScreen }
        GameState gameState = GameState.StartScreen;
        Song Music;

        public void CreateEnemy(EnemyType enemyType)
        {
            Random r = new Random();
            int startX = r.Next(1920);
            Enemy enemy = new Enemy(EnemyShip, new
            Vector2(startX, -100), 150.0f);
            enemy.SetAcrossMovement((float)startX / 1000.0f * 250.0f, 50.0f);
            enemy.Firing = true;
            enemyShipList.Add(enemy);
        }

        private void DrawStartScreen()
        {
            spriteBatch.Begin();
            spriteBatch.Draw(StartSplash, Vector2.Zero, null, Color.White);
            spriteBatch.DrawString(menufont, "Press ENTER to start game", new Vector2(700, 640), Color.White);
            spriteBatch.End();
        }

        private void DrawEndScreen()
        {
            spriteBatch.Begin();
            spriteBatch.Draw(EndSplash, Vector2.Zero, null, Color.White);
            spriteBatch.DrawString(menufont, "Final Score: " + score.ToString() + "\nPress ESC to Exit\nr to restart", new Vector2(820, 640), Color.White);
            spriteBatch.End();
        }

        //Visa poäng
        private void DrawScore()
        {
            spriteBatch.DrawString(font, "Score: " + score.ToString(), new Vector2(20, 30), Color.White);
        }

        private void UpdateSplashScreen()
        {
            KeyboardState keyState = Keyboard.GetState();
            if (gameState == GameState.StartScreen)
            {
                if (keyState.IsKeyDown(Keys.Enter))
                {
                    gameState = GameState.Running;
                    MediaPlayer.Play(Music);
                }
            }
            else if (gameState == GameState.EndScreen)
            {
                if (keyState.IsKeyDown(Keys.R))
                {
                    gameState = GameState.Running;
                    MediaPlayer.Play(Music);
                }
            }
        }
        public void CreateEnemyTime()
        {
            if (totalTime > 1.0f && totalTime < 1.5f)
                CreateEnemy(EnemyType.Ship);
            if (totalTime > 6.0f && totalTime < 6.5f)
                CreateEnemy(EnemyType.Ship);
            if (totalTime > 11.3f && totalTime < 14.3f)
            {
                CreateEnemy(EnemyType.Ship);
                score += 1;
            }
            if (totalTime > 23.0f && totalTime < 60.0f)
            {
                CreateEnemy(EnemyType.Ship);
                score += 5;
            }


        }
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.graphics.PreferredBackBufferWidth = 1920;
            this.graphics.PreferredBackBufferHeight = 1200;
            this.graphics.IsFullScreen = true;
            this.graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            StartSplash = Content.Load<Texture2D>("Start");
            BGTexture = Content.Load<Texture2D>("Background");
            EndSplash = Content.Load<Texture2D>("End");
            // Create our player, besides position we pass it the graphics device
            Texture2D shipStill = Content.Load<Texture2D>("Spaceship");
            Spaceship = new Player(graphics.GraphicsDevice, new Vector2(850.0f,
            800.0f), new Vector2(shipStill.Width / 2, shipStill.Height / 2));
            Spaceship.AddCell(shipStill);
            Texture2D shipForward = Content.Load<Texture2D>("Spaceship_acc");
            Spaceship.AddCell(shipForward);
            Texture2D shipLeft = Content.Load<Texture2D>("Spaceship_left");
            Spaceship.AddCell(shipLeft);
            Texture2D shipRight = Content.Load<Texture2D>("Spaceship_right");
            Spaceship.AddCell(shipRight);
            Blast = Content.Load<Texture2D>("Blast");
            EnemyShip = Content.Load<Texture2D>("EnemyShip");
            EBlast = Content.Load<Texture2D>("EBlast");
            font = Content.Load<SpriteFont>("DefaultFont");
            menufont = Content.Load<SpriteFont>("Font");
            MediaPlayer.Volume = 0.1f;
            MediaPlayer.IsRepeating = true;
            Music = Content.Load<Song>("TheVeldt");


        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }


        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();
            // TODO: Add your update logic here
            UpdateInput();

            Spaceship.Update(gameTime);
            if (gameState == GameState.StartScreen || gameState == GameState.EndScreen)
                UpdateSplashScreen();
            else
            {
                float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
                buttonFireDelay -= elapsed;
                totalTime += elapsed;
                CreateEnemyTime();
                for (int i = 0; i < playerFireballList.Count; i++)
                {
                    playerFireballList[i].Update(gameTime);
                    if (playerFireballList[i].Position.Y < -100.0f)
                        playerFireballList.RemoveAt(i);
                }
                for (int i = 0; i < enemyShipList.Count; i++)
                {
                    enemyShipList[i].Update(gameTime);
                    if (enemyShipList[i].Firing)
                    {
                        Fireball fireball = new Fireball(EBlast,
                        new Vector2(enemyShipList[i].Position.X + 9.0f, enemyShipList[i].Position.Y + 30.0f), -300.0f);
                        enemyFireballList.Add(fireball);
                        enemyShipList[i].Firing = false;
                    }
                    int collide = enemyShipList[i].CollisionBall(playerFireballList);
                    if (collide != -1)
                    {
                        enemyShipList.RemoveAt(i);
                        playerFireballList.RemoveAt(collide);
                        score += 100;
                        CreateEnemy(EnemyType.Ship);
                    }
                    else if (enemyShipList[i].Position.Y > 1200.0f)
                    {
                        enemyShipList.RemoveAt(i);
                        score += 2;
                    }


                }
                for (int i = 0; i < enemyFireballList.Count; i++)
                {
                    enemyFireballList[i].Update(gameTime);
                    Spaceship.CollisionTest(enemyFireballList[i].Position);
                    if (enemyFireballList[i].Position.Y > 1200.0f)
                        enemyFireballList.RemoveAt(i);
                }
                if (!Spaceship.Alive)
                {
                    gameState = GameState.EndScreen;
                    enemyFireballList.Clear();
                    enemyShipList.Clear();
                    playerFireballList.Clear();
                }

                base.Update(gameTime);

            }

        }

        protected void UpdateInput()
        {
            KeyboardState keyState = Keyboard.GetState();

            if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
            {
                Spaceship.Accelerate();
            }
            else if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
            {
                Spaceship.MoveReverse();
            }
            else if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
            {
                Spaceship.TurnLeft();
            }
            else if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
            {
                Spaceship.TurnRight();
            }
            else
            {
                Spaceship.Still();
            }
            if (keyState.IsKeyDown(Keys.Space))
            {
                if (buttonFireDelay <= 0.0f)
                {
                    Fireball shotLeft = new Fireball(Blast,
                    new Vector2(Spaceship.Position.X - 3.0f, Spaceship.Position.Y - 5.0f),
                    300.0f);
                    playerFireballList.Add(shotLeft);
                    Fireball shotRight = new Fireball(Blast,
                    new Vector2(Spaceship.Position.X + 18.0f, Spaceship.Position.Y - 5.0f),
                    300.0f);
                    playerFireballList.Add(shotRight);
                    buttonFireDelay = 0.25f;
                }
            }
            if (keyState.IsKeyDown(Keys.R))
            {
                enemyFireballList.Clear();
                enemyShipList.Clear();
                playerFireballList.Clear();
                Spaceship.Position = new Vector2(850.0f, 800.0f);
                score = 0;
                Spaceship.Alive = true;
                totalTime = 0.0f;
                MediaPlayer.Stop();
                MediaPlayer.Play(Music);
            }
            if (keyState.IsKeyDown(Keys.NumPad8))
                MediaPlayer.Volume += 0.01f;
            else if (keyState.IsKeyDown(Keys.NumPad2))
                MediaPlayer.Volume -= 0.01f;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            if (gameState == GameState.StartScreen)
            {
                DrawStartScreen();
            }
            else if (gameState == GameState.Running)
            {
                spriteBatch.Begin();
                spriteBatch.Draw(BGTexture, Vector2.Zero, Color.White);
                Spaceship.Draw(spriteBatch);
                // Rita upp alla projektiler
                foreach (Fireball f in playerFireballList)
                    f.Draw(spriteBatch);
                foreach (Fireball f in enemyFireballList)
                    f.Draw(spriteBatch);
                foreach (Enemy e in enemyShipList)
                    e.Draw(spriteBatch);
                DrawScore();
                spriteBatch.End();

            }
            else if (gameState == GameState.EndScreen)
            {
                DrawEndScreen();
                MediaPlayer.Stop();
            }
            base.Draw(gameTime);
        }
    }
}